package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.dto.AlertDataDto;
import com.zzyl.serve.dto.AlertDataPageReqDto;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.service.IAlertDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.security.access.AccessDeniedException; // 导入 AccessDeniedException
import javax.naming.NoPermissionException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 报警数据Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-26
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return alertDataMapper.selectById(id);
    }

    /**
     * 处理报警数据
     *
     * @param
     * @return 处理报警数据
     */

    @Override
    public void handleAlertData(AlertDataDto alertDataDto) {

        Long processorId = SecurityUtils.getUserId();
        String name = SecurityUtils.getUsername();
        LambdaQueryWrapper<AlertData> wrapper = Wrappers.<AlertData>lambdaQuery().eq(AlertData::getId, alertDataDto.getId());

        AlertData data = getOne(wrapper);
        if (data == null) {
            return;
        }
        data.setProcessingResult(alertDataDto.getProcessingResult());
        data.setProcessingTime(alertDataDto.getProcessingTime());
        data.setProcessorId(processorId);
        data.setStatus(1);
        data.setProcessorName(name);
        updateById(data);


    }

    /**
     * 查询报警数据列表
     *
     * @param dto 报警数据
     * @return 报警数据
     */

    @Override
    public TableDataInfo<AlertData> selectAlertDataPageList(AlertDataPageReqDto dto) throws NoPermissionException {

        Long processorId = SecurityUtils.getUserId();
        //通过处理人ID查询，该处理人的权限
        Long roleId = alertDataMapper.selectRoleIdByUserId(processorId);
        //如果是超级管理员，直接返回所有数据
        if(roleId == 1){
            LambdaQueryWrapper<AlertData> wrapper = Wrappers.<AlertData>lambdaQuery()
                    .eq(dto.getDeviceName() != null, AlertData::getDeviceName, dto.getDeviceName())
                    .eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
                    .between(dto.getStartTime() != null && dto.getEndTime() != null,
                            AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime());
            Page<AlertData> page = page(Page.of(dto.getPageNum(), dto.getPageSize()), wrapper);
            page.getRecords().forEach(alertData -> {
                String nickName = alertDataMapper.selectNickNameByIotId(alertData.getIotId());
                alertData.setNickName(nickName);
            });
            TableDataInfo<AlertData> tableDataInfo = new TableDataInfo<>();
            tableDataInfo.setCode(HttpStatus.SUCCESS);
            tableDataInfo.setMsg("查询成功");
            tableDataInfo.setTotal(page.getTotal());
            tableDataInfo.setRows(page.getRecords());
            return tableDataInfo;
        }else if(roleId == 100){
            //设置权限
            LambdaQueryWrapper<AlertData> wrapper = Wrappers.<AlertData>lambdaQuery()
                    .eq(AlertData::getUserId, processorId)
                    .eq(dto.getDeviceName() != null, AlertData::getDeviceName, dto.getDeviceName())
                    .eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
                    .between(dto.getStartTime() != null && dto.getEndTime() != null,
                            AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime());
            Page<AlertData> page = page(Page.of(dto.getPageNum(), dto.getPageSize()), wrapper);
            // 查询设备昵称,设置昵称
            page.getRecords().forEach(alertData -> {
                String nickName = alertDataMapper.selectNickNameByIotId(alertData.getIotId());
                alertData.setNickName(nickName);
            });
            TableDataInfo<AlertData> tableDataInfo = new TableDataInfo<>();
            tableDataInfo.setCode(HttpStatus.SUCCESS);
            tableDataInfo.setMsg("查询成功");
            tableDataInfo.setTotal(page.getTotal());
            tableDataInfo.setRows(page.getRecords());
            return tableDataInfo;
                }
        throw new AccessDeniedException("没有访问报警数据的权限，请联系管理员授权");
        }
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {
        return List.of();
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return alertDataMapper.insert(alertData);
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return alertDataMapper.updateById(alertData);
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return alertDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return alertDataMapper.deleteById(id);
    }
}
